package lxs.swift.tool.http;


import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;

public class Sender {
    protected final Config config;
    protected HttpURLConnection connection;
    protected OutputStream out;

    public Sender(Config config) {
        this.config = config;
    }

    protected void open() {
        String url = this.config.assembleURL();
        try {
            java.net.URL realUrl = new java.net.URL(url);
            // 打开和URL之间的连接
            HttpURLConnection connection = ((HttpURLConnection) realUrl.openConnection(config.proxy));
            this.config.headerMap.forEach((k, v) -> {
                if (k == null || k.isEmpty() || v == null || v.toString().isEmpty()) return;
                v.forEach(val -> connection.addRequestProperty(k, val.toString()));
            });
            if (!config.method.isEmpty()) {
                connection.setRequestMethod(config.method);
                if (config.method.equalsIgnoreCase("GET")) connection.setDoOutput(false);
                else if (config.method.equalsIgnoreCase("HEAD")) connection.setDoOutput(false);
                else if (config.method.equalsIgnoreCase("OPTIONS")) connection.setDoOutput(false);
                else connection.setDoOutput(true);
            }
            connection.setConnectTimeout(this.config.connectTimeout);
            connection.setReadTimeout(this.config.readTimeout);
            connection.setInstanceFollowRedirects(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            this.connection = connection;
            connection.connect();
            if (connection.getDoOutput()) this.out = this.connection.getOutputStream();
        } catch (IOException e) {
            close();
            throw new RuntimeException(e);
        }
    }

    public void write(byte[] bytes) {
        try {
            if (this.connection == null) open();
            if (this.out == null) {
                this.out = this.connection.getOutputStream();
            }
            this.out.write(bytes);
        } catch (IOException e) {
            close();
            throw new RuntimeException(e);
        }
    }

    protected void close() {
        try {
            if (this.out != null) this.out.close();
            if (this.connection != null) this.connection.disconnect();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public Receiver read() {
        try {
            out.flush();
        } catch (IOException e) {
            close();
            throw new RuntimeException(e);
        }
        return new Receiver(this);
    }

    public static void trustAllHttpsCertificates() {
        try {
            javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
            javax.net.ssl.TrustManager tm = new miTM();
            trustAllCerts[0] = tm;
            javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                    .getInstance("SSL");
            sc.init(null, trustAllCerts, null);
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
                    .getSocketFactory());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    private static class miTM implements javax.net.ssl.TrustManager,
            javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {

        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }
    }

    public static SenderBuilder config(Config config) {
        return new SenderBuilder(config);
    }

    public static class SenderBuilder {
        private final Config config;

        private SenderBuilder(Config config) {
            this.config = config;
        }

        public Receiver get() {
            config.method = "GET";
            Getter getter = new Getter(config);
            return getter.read();
        }

        public XFormPoster xform() {
            return new XFormPoster(config);
        }

        public Sender sender() {
            return new Sender(config);
        }

        public FormPoster form() {
            return new FormPoster(config);
        }

        public JsonPoster json() {
            return new JsonPoster(config);
        }

        public JsonArrayPoster jsonArray() {
            return new JsonArrayPoster(config);
        }
    }
}
